package com.day02;

import java.util.Arrays;
import java.util.Random;

public class 归并排序02 {
    /**
     * 将数组两两递归分开
     *
     * @param arr
     * @param left
     * @param right
     * @param temp
     */
    public static void mergeSort(int[] arr, int left, int right, int[] temp) {
        int mid = (left + right) / 2;
        if (left < right) {
            mergeSort(arr, left, mid, temp);
            mergeSort(arr, mid + 1, right, temp);
            merge(arr, left, mid, right, temp);
        }
    }

    public static void merge(int[] arr, int left, int mid, int right, int[] temp) {
        int i = left;
        int j = mid + 1;
        int t = 0;
        while (i <= mid && j <= right) {
            if (arr[i] < arr[j]) {
                temp[t] = arr[i];
                i++;
            } else {
                temp[t] = arr[j];
                j++;
            }
            t++;
        }
        while (i <= mid) {
            temp[t] = arr[i];
            t++;
            i++;
        }
        while (j <= right) {
            temp[t] = arr[j];
            t++;
            j++;
        }
        int n = 0;
        int tempLeft = left;
        while (tempLeft <= right) {
            arr[tempLeft] = temp[n];
            tempLeft++;
            n++;
        }
    }

    public static void main(String[] args) {
        int arr[] = new int[10];
        int arr1[] = new int[10];
        int temp[] = new int[10];
        Random random = new Random();
        for (int i = 0; i < arr.length; i++) {
            arr[i] = random.nextInt(100);
        }
        System.arraycopy(arr, 0, arr1, 0, arr.length);
        Arrays.sort(arr1);
        mergeSort(arr, 0, arr.length - 1, temp);
        boolean flag = true;
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] == arr1[i]) {
                flag = flag && true;
            } else {
                flag = false;
            }
        }
        System.out.println("归并排序结果是否正确: " + (flag ? "√" : "×"));
    }
}
